package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.mq.MQConstants;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.vo.PageResult;
import com.leyou.item.dto.*;
import com.leyou.item.entity.Sku;
import com.leyou.item.entity.Spu;
import com.leyou.item.entity.SpuDetail;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.mapper.SpuDetailMapper;
import com.leyou.item.mapper.SpuMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 虎哥
 */
@Service
public class GoodsService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private SpuDetailMapper detailMapper;

    @Autowired
    private SkuMapper skuMapper;

    /*
    SELECT *
    FROM tb_spu
    WHERE `name` LIKE "%小%"	AND saleable = 1
    ORDER BY update_time DESC
     */
    public PageResult<SpuDTO> querySpuByPage(Integer page, Integer rows, String key, Boolean saleable) {
        // 分页
        PageHelper.startPage(page, rows);

        // 创建Example条件
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        // 1.关键字搜索
        if (StringUtils.isNotBlank(key)) {
            criteria.andLike("name", "%" + key + "%");
        }
        // 2.上下架
        if (saleable != null) {
            criteria.andEqualTo("saleable", saleable);
        }
        // 3.排序条件
        example.setOrderByClause("update_time DESC");

        List<Spu> list = spuMapper.selectByExample(example);

        if (CollectionUtils.isEmpty(list)) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }

        // 4.数据解析
        List<SpuDTO> dtoList = BeanHelper.copyWithCollection(list, SpuDTO.class);
        PageInfo<Spu> info = new PageInfo<>(list);

        // 处理分类和品牌的名称
        handleCategoryAndBrandName(dtoList);
        return new PageResult<>(info.getTotal(), info.getPages(), dtoList);
    }

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    private void handleCategoryAndBrandName(List<SpuDTO> dtoList) {
        for (SpuDTO spuDTO : dtoList) {
            // 查询分类名称
            List<Long> idList = spuDTO.getCategoryIds();
            // 查询分类，并且把分类中的名称取出，拼接
            String name = categoryService.queryByIds(idList)
                    .stream()
                    .map(CategoryDTO::getName)
                    .collect(Collectors.joining("/"));
            spuDTO.setCategoryName(name);
            // 查询品牌名称
            BrandDTO brand = brandService.queryById(spuDTO.getBrandId());
            spuDTO.setBrandName(brand.getName());
        }
    }

    @Transactional
    public void saveGoods(SpuDTO spuDTO) {
        // 1.新增spu
        Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
        spu.setSaleable(false);
        int count = spuMapper.insertSelective(spu);
        if (count != 1) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

        // 2.新增spuDetail
        SpuDetailDTO spuDetail = spuDTO.getSpuDetail();
        spuDetail.setSpuId(spu.getId());
        count = detailMapper.insertSelective(BeanHelper.copyProperties(spuDetail, SpuDetail.class));

        // 3.新增Sku
        insertSku(spuDTO, spu);

    }

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Transactional
    public void updateSaleable(Long id, Boolean saleable) {
        // 1.更新spu UPDATE tb_spu SET saleable = 0 WHERE id = 1
        Spu spu = new Spu();
        spu.setId(id);
        spu.setSaleable(saleable);
        // 根据id，更新spu中的非空字段
        spuMapper.updateByPrimaryKeySelective(spu);

        // 2.更新sku UPDATE tb_sku
        // 2.1.sku， 封装要更新的数据 SET `enable` = 0
        Sku sku = new Sku();
        sku.setEnable(saleable);
        // 2.2.Example是更新的匹配条件 WHERE spu_id = 1;
        Example example = new Example(Sku.class);
        example.createCriteria().andEqualTo("spuId", id);

        skuMapper.updateByExampleSelective(sku, example);

        // 发送MQ消息
        String routingKey = saleable ? MQConstants.RoutingKey.ITEM_UP_KEY : MQConstants.RoutingKey.ITEM_DOWN_KEY;
        amqpTemplate.convertAndSend(MQConstants.Exchange.ITEM_EXCHANGE_NAME, routingKey, id);
    }

    public SpuDetailDTO queryDetailBySpuId(Long id) {
        SpuDetail spuDetail = detailMapper.selectByPrimaryKey(id);
        if (spuDetail == null) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyProperties(spuDetail, SpuDetailDTO.class);
    }

    public List<SkuDTO> querySkuBySpuId(Long id) {
        Sku sku = new Sku();
        sku.setSpuId(id);
        List<Sku> list = skuMapper.select(sku);
        if (CollectionUtils.isEmpty(list)) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(list, SkuDTO.class);
    }

    @Transactional
    public void updateGoods(SpuDTO spuDTO) {
        Long spuId = spuDTO.getId();
        // 查询sku数量
        Sku sku = new Sku();
        sku.setSpuId(spuId);
        int size = skuMapper.selectCount(sku);
        if (size > 0) {
            // 删除sku
            int count = skuMapper.delete(sku);
            if (count != size) {
                throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
            }
        }

        // 修改spu, 更新spu中的非空字段，无需修改的字段，需要设置为null
        Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
        spu.setSaleable(null);
        spu.setCreateTime(null);
        spu.setUpdateTime(null);
        int count = spuMapper.updateByPrimaryKeySelective(spu);
        if (count != 1) {
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }

        // 修改spuDetail
        SpuDetail spuDetail = BeanHelper.copyProperties(spuDTO.getSpuDetail(), SpuDetail.class);
        count = detailMapper.updateByPrimaryKeySelective(spuDetail);
        if (count != 1) {
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }

        // 新增sku
        insertSku(spuDTO, spu);
    }

    private void insertSku(SpuDTO spuDTO, Spu spu) {
        int count;
        List<SkuDTO> skus = spuDTO.getSkus();
        for (SkuDTO skuDTO : skus) {
            skuDTO.setSpuId(spu.getId());
            // 默认商品下架
            skuDTO.setEnable(false);
        }
        List<Sku> skuList = BeanHelper.copyWithCollection(skus, Sku.class);

        count = skuMapper.insertList(skuList);
        if (count != skuList.size()) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }

    public SpuDTO querySpuById(Long id) {
        // 查询spu
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if (spu == null) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        SpuDTO spuDTO = BeanHelper.copyProperties(spu, SpuDTO.class);

        // 查询SpuDetail
        spuDTO.setSpuDetail(queryDetailBySpuId(id));
        // 查询skus
        spuDTO.setSkus(querySkuBySpuId(id));

        return spuDTO;
    }

    public List<SkuDTO> querySkuByIds(List<Long> ids) {
        List<Sku> list = skuMapper.selectByIdList(ids);
        if (CollectionUtils.isEmpty(list)) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(list, SkuDTO.class);
    }

    @Transactional
    public void minusStock(Map<Long, Integer> skuMap) {
        for (Map.Entry<Long, Integer> entry : skuMap.entrySet()) {
            // 获取商品信息
            Long skuId = entry.getKey();
            Integer num = entry.getValue();
            int count = skuMapper.minusStock(skuId, num);
            if(count != 1){
                throw new LyException(ExceptionEnum.STOCK_NOT_ENOUGH);
            }
        }
    }
}
